<script setup lang="ts">
import {computed, ref} from 'vue';
import {
  AllTradeMark, HasSaleAttr,
  HasSaleAttrResponseData, SaleAttr,
  SaleAttrResponseData,
  SpuData,
  SpuHasImg, SpuImg,
  Trademark, SaleAttrValue
} from "@/api/product/spu/type.ts";
import {
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSaleAttr,
  reqAddOrUpdateSpu
} from "@/api/product/spu";
import {ElMessage} from "element-plus";

let $emit = defineEmits(['changeScence'])
const cancel = () => {
  $emit('changeScence', {flag:0,params:'update'})
}

//存储已有的SPU数据
let MYAllTradeMark = ref<Trademark[]>([])
//商品图片
let imgList = ref<SpuImg[]>([])
//存储已有的SPU的销售属性
let saleAttr = ref<SaleAttr[]>([])
//存储全部的销售属性
let allSaleAttr = ref<HasSaleAttr[]>([])

//存储已有的SPU对象
let SpuParams = ref<SpuData>({
  spuName: '',
  category3Id: 0,
  tmId: 0,
  description: '',
  spuImageList: [],
  spuSaleAttrList: []
})

//控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false)
//存储预览图片地址
let dialogImageUrl = ref<string>('')

//计算属性：未选择的销售属性
let unSelectSaleAttr = computed(() => {
  return allSaleAttr.value.filter((item) => {
    return saleAttr.value.every((item1) => {
      return item1.saleAttrName !== item.name
    })
  })
})

let saleAttrIdAndValueName = ref<string>('')


//子组件书写一个方法
const initHasSpuData = async (spu: SpuData) => {
  //spu:即为父组件传递过来的已有的SPU对象[不完整]
  SpuParams.value = spu
  //获取全部品牌的数据
  let result: AllTradeMark = await reqAllTradeMark()
  //获取某一个品牌旗下全部售卖商品的图片
  let result1: SpuHasImg = await reqSpuImageList(spu.id as number)
  //获取已有的SPU销售属性的数据
  let result2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
  //获取整个项目全部SPU的销售属性
  let result3: HasSaleAttrResponseData = await reqAllSaleAttr()
  //存储全部品牌的数据
  MYAllTradeMark.value = result.data
  //SPU对应商品图片
  imgList.value = result1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  console.log(result2)
  //存储已有的SPU的销售属性
  saleAttr.value = result2.data
  //存储全部的销售属性
  allSaleAttr.value = result3.data
}

//照片墙点击预览按钮的时候触发的钩子
const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  //对话框弹出来
  dialogVisible.value = true
}
//照片墙删除文件钩子
const handleRemove = (file: any) => {
  //删除图片
  imgList.value = imgList.value.filter((item) => {
    return item.url !== file.url
  })
}
//照片钱上传成功之前的钩子约束文件的大小与类型
const handlerUpload = (file: any) => {
  if (
      file.type == 'image/png' ||
      file.type == 'image/jpeg' ||
      file.type == 'image/gif'
  ) {
    if (file.size / 1024 / 1024 < 3) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件务必小于3M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件务必PNG|JPG|GIF',
    })
    return false
  }
}

const addSaleAttr = () => {

  /* *
   *     baseSaleAttrId: number | string
   *     saleAttrName: string
   *     spuSaleAttrValueList: SpuSaleAttrValueList
   */
  let [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  //准备一个新的销售属性对象：将来带给服务器即可
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: []
  }
  //追加到数组当中
  saleAttr.value.push(newSaleAttr)
  //清空收集的数据
  saleAttrIdAndValueName.value = ''
}

const toLook = (row: SaleAttr) => {
  console.log(row)
  //整理收集的属性值的ID与属性值的名字
  const {baseSaleAttrId, saleAttrValue} = row
  //整理成服务器需要的属性值形式
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string
  }
  //非法情况判断
  if ((saleAttrValue as string).trim() == '') {
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }
  //判断属性值是否在数组当中存在
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName === saleAttrValue
  })
  if (repeat) {
    ElMessage({
      type: 'error',
      message: '属性值已经存在',
    })
    return
  }
  //追加到数组当中
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  //切换为查看模式
  row.flag = false
}

const toEdit = (row: SaleAttr) => {
  row.flag = true
  row.saleAttrValue = ''
}

const save = async () => {
  //整理SPU的图片
  SpuParams.value.spuImageList = imgList.value.map((item) => {
    return {
      imgName: item.name,//图片名字
      imgUrl: (item.response && item.response.data) || item.url//图片地址
    }
  })
  //整理SPU的销售属性
  SpuParams.value.spuSaleAttrList = saleAttr.value
  let result = await reqAddOrUpdateSpu(SpuParams.value)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: SpuParams.value.id ? '修改成功' : '添加成功',
    })
    //切换为场景0
    $emit('changeScence', {
      flag:0,
      params: SpuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'error',
      message: SpuParams.value.id ? '修改失败' : '添加失败',
    })
  }
}

//添加一个新的SPU初始化请求方法
const initAddSpu = async (c3Id: number | string) => {
  //清空数据
  Object.assign(SpuParams.value, {
    category3Id: '', //收集三级分类的ID
    spuName: '', //SPU的名字
    description: '', //SPU的描述
    tmId: '', //品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
  })
  //清空照片
  imgList.value = []
  //清空销售属性
  saleAttr.value = []
  saleAttrIdAndValueName.value = ''
  //存储三级分类的ID
  SpuParams.value.category3Id = c3Id
  //获取全部品牌的数据
  let result: AllTradeMark = await reqAllTradeMark()
  let result1: HasSaleAttrResponseData = await reqAllSaleAttr()
  //存储数据
  MYAllTradeMark.value = result.data
  allSaleAttr.value = result1.data
}


//对外暴露方法
defineExpose({
  initHasSpuData,
  initAddSpu
})

</script>

<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input placeholder="请你输入SPU名称" v-model="SpuParams.spuName"></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId">
        <el-option v-for="item in MYAllTradeMark" :key="item.id" :label="item.tmName" :value="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" placeholder="请你输入SPU描述" v-model="SpuParams.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
          v-model:file-list="imgList"
          action="/api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="handlerUpload"
      >
        <el-icon>
          <Plus/>
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" style="width: 100%;height: 100%"/>
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性" size="normal">
      <!-- 展示销售属性的下拉菜单 -->
      <el-select v-model="saleAttrIdAndValueName"
                 :placeholder="unSelectSaleAttr.length?`还未选择${unSelectSaleAttr.length}个`:'无'">
        <el-option v-for="item in unSelectSaleAttr" :label="item.name" :key="item.id"
                   :value="`${item.id}:${item.name}`"></el-option>
      </el-select>
      <el-button
          :disabled="!saleAttrIdAndValueName"
          style="margin-left: 10px"
          type="primary"
          size="default"
          icon="Plus"
          @click="addSaleAttr"
      >
        添加属性
      </el-button>
      <!-- table展示销售属性与属性值的地方 -->
      <el-table border style="margin: 10px 0px" :data="saleAttr">
        <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80px"
        ></el-table-column>
        <el-table-column
            label="销售属性名字"
            width="120px"
            prop="saleAttrName"
        ></el-table-column>

        <el-table-column label="销售属性值">
          <!-- row:即为当前SPU已有的销售属性对象 -->
          <template #="{ row, $index }">
            <el-tag
                class="mx-1"
                closable
                style="margin: 0 5px"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                v-for="(item, index) in row.spuSaleAttrValueList"
                :key="row .id"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
                @blur="toLook(row)"
                v-model="row.saleAttrValue"
                v-if="row.flag ===true"
                placeholder="请你输入属性值"
                size="small"
                style="width: 100px"
            ></el-input>
            <el-button v-else type="primary" size="small" icon="Plus" @click="toEdit(row)"></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px">

          <template #="{ row, $index }">
            <el-button
                type="primary"
                size="small"
                icon="Delete"
                @click="saleAttr.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="save" :disabled="saleAttr.length<=0">保存</el-button>
      <el-button type="primary" size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>

</style>